package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnLikesBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.UnLikesBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author XHui
 * @Since 2024/3/3 14:46
 * @Version 1.0
 */
@Service
public class ApUnLikesBehaviorServiceImpl implements ApUnLikesBehaviorService {

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private ApBehaviorEntryService apBehaviorEntryService;


    @Override
    public ResponseResult unlikesBehavior(UnLikesBehaviorDTO dto) {

        ApBehaviorEntry entry = apBehaviorEntryService.getApBehaviorEntryByUserIdOrEquipmentId(dto.getEquipmentId());

        // 1. 根据articleId查询该文章的不喜欢行为数据
        // 1.1 查询 行为实体 与 文章操作 的关联关系
        ApUnlikesBehavior apUnlikesBehavior = apBehaviorEntryService.findBehaviorTraceByEntryIdAndArticleId(
                dto.getArticleId(), dto.getEquipmentId(), ApUnlikesBehavior.class
        );

        // 2. 若行为实体 不喜欢该文章的记录不存在， 只能进行不喜欢
        Short type = dto.getType();
        if(apUnlikesBehavior == null &&
                type == ApUnlikesBehavior.Type.UNLIKE.getCode()){
            // 2.1 新增不喜欢的记录
            apUnlikesBehavior = new ApUnlikesBehavior();
            apUnlikesBehavior.setEntryId(entry.getId());
            apUnlikesBehavior.setArticleId(dto.getArticleId());
            apUnlikesBehavior.setType(type);
            apUnlikesBehavior.setCreatedTime(new Date());
            mongoTemplate.insert(apUnlikesBehavior);

        } else if (apUnlikesBehavior != null &&
                type == ApUnlikesBehavior.Type.CANCEL.getCode()) {
            // 3. 若行为实体 不喜欢该文章的记录存在， 只能进行取消不喜欢
            mongoTemplate.remove(apUnlikesBehavior);
        } else {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "操作不合法");
        }

        // 4. 返回结果
        return ResponseResult.okResult();
    }
}
